<?php 
/**
 * Class description
 *
 * @since 8 мая 2010
 * @author diotheos
 */
class Lib_Integrator_Site_Ria {
	/**
	 * @var Lib_Integrator_Site_Ria_Connector
	 */
	private $_connector;
	/**
	 * @var Zend_Config
	 */
	private $_config;
	/**
	 * Function description
	 *
	 * @since 8 мая 2010
	 * @author diotheos
	 */
	public function __construct() {
		echo "<div>Creating global integrator</div>";
		$this->_config = new Zend_Config_Ini(APPLICATION_PATH . "/../library/Lib/Integrator/Site/Ria/config.ini", 'default');
	}
	/**
	 * Function description
	 * 
	 * @since 8 мая 2010
	 * @author diotheos
	 * @return void
	 */
	public function setConnector(Lib_Integrator_Site_Ria_Connector $connector){
		$this->_connector = $connector;
		echo "<div>Linking connector with global integrator</div>";
	}
	/**
	 * Function description
	 * 
	 * @since 8 мая 2010
	 * @author diotheos
	 * @return Lib_Integrator_Site_Ria_Connector
	 */
	public function getConnector(){
		return $this->_connector;
	}
	
	/**
	 * Function description
	 * 
	 * @since 8 мая 2010
	 * @author diotheos
	 * @return void
	 */
	public function integrateAll(){
		
//		$this->integrateCategories();
//        $this->integrateMarks();
//        $this->integrateModels();
//        $this->integrateColors();
//        $this->integrateFuel();
//        $this->integrateDrive();
//        $this->integrateGear();
//        $this->integrateBody();
//        $this->integrateCurrency();
//        $this->integrateStates();
//        $this->integrateCities();
        $this->integrateViaDoctrine();
        
//		$this->fallbackCategories();
//		$this->fallbackModels();
//		$this->fallbackMarks();
//		$this->fallbackColors();
//		$this->fallbackFuel();
//		$this->fallbackDrive();
//		$this->fallbackGear();
//		$this->fallbackBody();
//		$this->fallbackCurrency();
//        $this->fallbackCities();
//        $this->fallbackStates();
        
	}
	/**
	 * Function description
	 * 
	 * @since 9 мая 2010
	 * @author diotheos
	 * @return void
	 */
	public function __call($name, $arguments){
		if(strpos($name, 'integrate') !== false){
			$name = str_replace('integrate','',$name);
			$name = strtolower($name);
			if($this->_config->$name){
				echo "<div>Starting $name integration</div><div style='padding-left:25px;'>";        
		        $integrator = new Lib_Integrator_Site_Ria_Common_Base($this->getConnector(), $this->_config, $name);
		        $integrator->integrate();
		        unset($integrator);
		        echo "</div><div>End of $name integration</div>";
			} 			
		} else  if(strpos($name, 'fallback') !== false){
            $name = str_replace('fallback','',$name);
            $name = strtolower($name);
            if($this->_config->$name){
                echo "<div>Starting $name clearing</div><div style='padding-left:25px;'>";        
                $integrator = new Lib_Integrator_Site_Ria_Common_Base($this->getConnector(), $this->_config, $name);
                $integrator->fallback();
                unset($integrator);
                echo "</div><div>End of $name clearing</div>";
            }
        }
	}
	/**
	 * Function description
	 * 
	 * @since 16 мая 2010
	 * @author diotheos
	 * @return void
	 */
	public function integrateViaDoctrine(){
        $integrator = new Lib_Integrator_Site_Ria_Common_Base($this->getConnector(), $this->_config);
        $localConnection = $integrator->getLocalConnection();
        $remoteConnection = $integrator->getConnection();
        Doctrine_Core::loadModels(APPLICATION_PATH.'/models/Model',Doctrine::MODEL_LOADING_PEAR,'Model_');

        $autos = $remoteConnection->createQuery()
            ->select('auto.*, client.*, phones.*, media.*')
            ->from('Model_Auto3_AutoDBO auto')
            ->leftJoin('auto.Gallery media WITH media.is_video = ?', 0)
            ->innerJoin('auto.Clients client WITH client.email <> ""')
            ->innerJoin('client.Model_Passport_Phones3DBO phones')
            ->where('auto.price NOT BETWEEN ? AND ?', array('1','199'))
            ->andWhere('auto.description <> ""')
            ->andWhere('auto.saled_date = ?', "0000-00-00 00:00:00")
            ->andWhere('auto.group_id = ?', 0)
            ->orderBy('auto.auto_id asc')
            ->limit(10)
            ->execute()
            ->toArray();
        
        echo "<pre>";
        	print_r($autos[0]);
        echo "</pre>";    
        $userCollection = new Doctrine_Collection('User');
        $carCollection = new Doctrine_Collection('Car');
        $k = 0;
        foreach($autos as $auto){
        	$client = $auto['Clients'];
        	$userCollection[$k]->email = $client['email'];
        	$userCollection[$k]->password = $client['email'];
        	$userCollection[$k]->status = User::STATUS_ACTIVE;
        	$userCollection->setKeyColumn('email');
//        	$userTable = UserTable::getInstance();
//        	$userTable->
            $k++;
        	
        }

        $userCollection->save();
//        echo "<pre>";
//        	print_r($r->toArray());
//        echo "</pre>";
        die('Asta la vista');    
	}
	
	/**
	 * Function description
	 * 
	 * @since 11 мая 2010
	 * @author diotheos
	 * @return void
	 */
	public function integrateAutoUserMedia(){
//		$options = array(
//    'phpDocSubpackage'      => 'Models',
//    'phpDocName'            => 'RIA-MULTIMEDIA',
//    'phpDocEmail'           => 'www.riamultimedia.com',
//    'phpDocPackage'         => 'ORM',
//    'pearStyle'             => true,
//    'generateBaseClasses'   => true,
//    'packagesPrefix'        => 'Package',
//    'packagesPath'          => '',
//    'packagesFolderName'    => 'packages',
//    'suffix'                => '.php',
//    'suffixClass'           => 'DBO',
//    'baseClassPrefix'       => 'Base_',
//    'baseClassesDirectory'  => '',
//    'classPrefixFiles'      => '',
//    'classPrefix'           => 'Model_'.$database_global.'_',
//    'baseClassName'         => 'Doctrine_Record');
		$importer = new Doctrine_Import_Builder();
		echo("<div>Starting Auto-Users-Media triplet integration</div><div style='padding-left:25px;'>");
		$integrator = new Lib_Integrator_Site_Ria_Common_Base($this->getConnector(), $this->_config);
		$localConnection = $integrator->getLocalConnection();
		$remoteConnection = $integrator->getConnection();
		
//		$carsConfig = $integrator->getConfigSection('cars');
//		$usersConfig = $integrator->getConfigSection('users');
//		$mediaConfig = $integrator->getConfigSection('media');

        $autoQuery = "
            SELECT
                a.* as auto, c.* as client
            FROM 
                auto3_ria.auto a
            INNER JOIN 
                    passport_ria.clients c
                ON
                    c.clientID = a.user_id
            INNER JOIN
                    passport_ria.phones3 p
                ON
                    c.clientID = p.user_id
            WHERE 
                    a.group_id = 0
                AND
                    (a.price NOT BETWEEN 1 AND 199)      
            ORDER BY a.auto_id ASC
            LIMIT 50     
        ";
        $autoAndUser = $remoteConnection->fetchAll($autoQuery);
        $userIds = array();
        $autoIds = array();
        
//        
//        echo "<pre>";
//        	print_r($autoAndUser);
//        echo "</pre>";
//        die('Asta la vista');
        foreach ($autoAndUser as $row){
        	$userIds[] = $row['clientID'];
        	if(isset($row['auto_id'])){
        		$autoIds[] = $row['auto_id'];
        	}
        }

        if(count($userIds)){
        	$userIds = implode(',',$userIds);
        	$autoIds = implode(',',$autoIds);
        	        $userQuery = "
			            SELECT
			                p.* as phone
			            FROM passport_ria.phones3 p
			            WHERE user_id in ($userIds);
			        ";
        	        
        	        $photoQuery = "
        	            SELECT
                            p.* as photo
                        FROM auto3_ria.photo p
                        WHERE auto_id in ($autoIds);
        	        ";
        	        
        	if(count($autoIds)){
        		$autoPhotos = $remoteConnection->fetchAll($photoQuery);
        	} else {
        		$autoPhotos = array();
        	}
        	$userPhones = $remoteConnection->fetchAll($userQuery);
        	
        	$usersToIntegrate = array();
        	$photosToIntegrate = array();
        	$phonesToIntegrate = array();
        	
        	echo "<pre>";
        		print_r($autoAndUser[0]);
        		print_r($userPhones[0]);
        		print_r($autoPhotos[0]);
        	echo "</pre>";
        	$d = 0;
        	foreach($autoAndUser as $userArr){
        		$usersToIntegrate[$d] = new User();
        		$usersToIntegrate[$d]->email = strtolower($userArr['email']);
        		$usersToIntegrate[$d]->password = $userArr['password'];
        		$d++;
        	}
//            echo "<pre>";
//            	print_r($usersToIntegrate);
//            echo "</pre>";
//            die('Asta la vista');
            $p = 0;
            foreach($userPhones as $phone){
                $phonesToIntegrate[$p] = new UserPhone();
                $phonesToIntegrate[$p]->phone = $phone['phone'];
                $phonesToIntegrate[$p]->phone_string = $phone['phone_str'];
                $phonesToIntegrate[$p]->user_id = $phone['user_id'];
                $p++;
            }
//            echo "<pre>";
//            	print_r($phonesToIntegrate[12]->toArray());
//            echo "</pre>";
            foreach($autoPhotos as $photo){
                
            }
        }
		echo("</div><div>End of Auto-Users-Media triplet integration</div>");
	}
}











